from flask import Flask, render_template, jsonify, request
from flask_cors import CORS
import json

def save_students_to_file(students):
    with open('students.json', 'w', encoding='utf-8') as file:
        json.dump(students, file, ensure_ascii=False, indent=4)

def load_students_from_file():
    try:
        with open('students.json', 'r', encoding='utf-8') as file:
            students = json.load(file)
            return students
    except FileNotFoundError:
        return []

app = Flask(__name__)
CORS(app)

# 加载学生数据
students = load_students_from_file()

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/nav')
def nav():
    return render_template('nav.html')

@app.route('/getStudents')
def getStudents():
    return jsonify(students)

@app.route('/addStudent', methods=['POST'])
def addStudent():
    student_data = request.json
    students.append(student_data)
    save_students_to_file(students)  # 保存到文件
    return jsonify(student_data), 201

@app.route('/deleteStudent', methods=['POST'])
def deleteStudent():
    student_id = request.form.get('student_id')
    if student_id:
        global students
        students = [student for student in students if student['student_id'] != student_id]
        save_students_to_file(students)  # 保存到文件
        return jsonify({'message': 'Student deleted successfully'}), 200
    else:
        return jsonify({'error': 'Student ID is required'}), 400

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=3556, debug=True)